package com.ruix.app.ui.stratum.lesson;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Spannable;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.OSS;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMImageMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.chat.EMVideoMessageBody;
import com.hyphenate.chat.EMVoiceMessageBody;
import com.hyphenate.chat.adapter.message.EMAMessage;
import com.hyphenate.chat.adapter.message.EMATextMessageBody;
import com.hyphenate.chat.adapter.message.EMAVoiceMessageBody;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.EaseUI;
import com.hyphenate.easeui.model.EaseAtMessageHelper;
import com.hyphenate.easeui.ui.EaseChatFragment;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.easeui.utils.EaseSmileUtils;
import com.hyphenate.easeui.widget.EaseAlertDialog;
import com.hyphenate.easeui.widget.EaseChatMessageList;
import com.hyphenate.easeui.widget.EaseVoiceRecorderView;
import com.hyphenate.easeui.widget.chatrow.EaseChatRow;
import com.hyphenate.easeui.widget.chatrow.EaseCustomChatRowProvider;
import com.hyphenate.exceptions.HyphenateException;
import com.ruix.app.R;
import com.ruix.app.cache.CacheFactory;
import com.ruix.app.constant.RuiXConstant;
import com.ruix.app.manager.UserManager;
import com.ruix.app.mapper.ClasssDetailMapper;
import com.ruix.app.mapper.LessonInfoMapper;
import com.ruix.app.mapper.MessageMapper;
import com.ruix.app.mapper.OssTokenMapper;
import com.ruix.app.model.ClassDetail;
import com.ruix.app.model.Classes;
import com.ruix.app.model.HXChatMessage;
import com.ruix.app.model.Lesson;
import com.ruix.app.model.LessonInfo;
import com.ruix.app.model.OssToken;
import com.ruix.app.model.User;
import com.ruix.app.model.viewmodel.InputSubItem;
import com.ruix.app.network.ALUploadFileParam;
import com.ruix.app.network.RXObserver;
import com.ruix.app.network.RequestFactory;
import com.ruix.app.network.exception.SendTimeException;
import com.ruix.app.ui.base.BaseActivity;
import com.ruix.app.util.LogUitl;
import com.ruix.app.util.RoleUtil;
import com.ruix.app.util.ToastUtil;
import com.ruix.app.widget.CommonTitleBar;
import com.ruix.app.widget.LessonInputView;
import com.ruix.app.widget.LessonInputVoiceView;
import com.ruix.app.widget.LessonTopView;
import com.ruix.app.widget.chatrow.ChatRowDiscuss;
import com.ruix.app.widget.chatrow.ChatRowImage;
import com.ruix.app.widget.chatrow.ChatRowLessonSumup;
import com.ruix.app.widget.chatrow.ChatRowMute;
import com.ruix.app.widget.chatrow.ChatRowText;
import com.ruix.app.widget.chatrow.ChatRowVoice;
import com.ruix.app.widget.dialog.CommonDialog;
import com.ruix.app.widget.dialog.CopyCommentDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import me.iwf.photopicker.PhotoPicker;

import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

/**
 * Created by hadexs on 2017/5/9.
 */

public class CaseLearningActivity extends BaseActivity implements EMMessageListener, View.OnClickListener, LessonInputView.OnOtherInputClickListener,LessonTopView.LessonTopViewLestener {

    public static Intent newIntent(Context context, Lesson lesson, Classes classes,String from) {
        Intent intent = new Intent(context, CaseLearningActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("lesson", lesson);
        bundle.putSerializable("classes",classes);
        bundle.putString("from",from);
        intent.putExtras(bundle);
        return intent;
    }

    protected static final int REQUEST_CODE_QUESTION = 1000;
    protected static final int REQUEST_CODE_CLEAR_TARGET = 2000;
    protected static final int REQUEST_CODE_SUMUP = 30000;
    protected static final int REQUEST_CODE_RECORD_AUDIO = 5;
    protected static final int REQUEST_CODE_FULLSCRAM = 40000;

    public Classes currentClasses;
    private Lesson lesson;
    private LessonInfo lessonInfo;
    private LessonTopView topView;
    private LessonInputView inputView;
//    private EaseChatFragment chatFragment;
    private EaseChatMessageList messageList;
    protected EaseVoiceRecorderView voiceRecorderView;
    protected SwipeRefreshLayout swipeRefreshLayout;
    protected ListView listView;
    private TextView topActionView;//收起展开
//    private TextView startTimeView; //共修时间
//    private boolean isAdviserOrHelper; //
    private boolean isCanSendVoice; //
    private boolean isMute; //是否禁言
    private CommonTitleBar titleBar;

    private CopyCommentDialog copyCotentDialog;

    private String toChatUsername;
    protected boolean isloading;
    protected boolean haveMoreData = true;
    protected int pagesize = 20;
    protected EMConversation conversation;
    private boolean isMessageListInited;
    private boolean isTeacherFriendCircle;//是否是师友圈

    private OSS ossClient;
    private OssToken ossToken;
    private String from;
//    private String voiceIdentifi;


    @Override
    protected boolean isUseBaseTitleBar() {
        return false;
    }

    public void setTitle(String title) {
        if (titleBar != null) {
            titleBar.setTitle(title);
        }
    }

    @Override
    protected int loadViewLayout() {
        return R.layout.activity_case_learning;
    }

    private void initCarrayData() {
        UserManager.sharedInstance().clearChatAuthers();
        Intent intent = getIntent();
        lesson = (Lesson) intent.getSerializableExtra("lesson");
        currentClasses =  (Classes)intent.getSerializableExtra("classes");
        from = intent.getStringExtra("from");
//        lesson =   UserManager.sharedInstance().getCurrentLesson();
        if (lesson == null || currentClasses == null){
            finish();
            return;
        }
        toChatUsername = lesson.getChatid();
        //权限判断
        isTeacherFriendCircle = currentClasses.isTeacherFriendCircle();
        String role = UserManager.getCurrentUser().getRole();
//        isAdviserOrHelper = RoleUtil.isAdviserOrHelperOrGuest(role);
        isCanSendVoice =  RoleUtil.isCanSendVoice(role,isTeacherFriendCircle);//判断是否有语音权限
        //todo
//        PathUtil.getInstance().initDirs(RuiXConstant.HX_APP_KEY,toChatUsername, RuiApplication.getAppContext());
    }

    @Override
    protected void initView() {
        initCarrayData();
        titleBar = (CommonTitleBar) findViewById(R.id.nav);
        topView = (LessonTopView) findViewById(R.id.rl_top_view_commtain);
        topActionView = (TextView) findViewById(R.id.tv_expand_top_view);
//        startTimeView = (TextView) findViewById(R.id.tv_create_time);
//        voiceRecorderView = (EaseVoiceRecorderView) findViewById(com.hyphenate.easeui.R.id.voice_recorder);
        messageList = (EaseChatMessageList) findViewById(com.hyphenate.easeui.R.id.message_list);
        listView = messageList.getListView();
//        View headerView =  View.inflate(this,R.layout.layout_case_learning_header,null);
//        startTimeView = (TextView) headerView.findViewById(R.id.tv_create_time);
//        listView.addHeaderView(headerView);



        swipeRefreshLayout = messageList.getSwipeRefreshLayout();
        swipeRefreshLayout.setColorSchemeResources(com.hyphenate.easeui.R.color.holo_blue_bright, com.hyphenate.easeui.R.color.holo_green_light,
                com.hyphenate.easeui.R.color.holo_orange_light, com.hyphenate.easeui.R.color.holo_red_light);

        RelativeLayout contentView = (RelativeLayout) findViewById(R.id.root_layout_contain);
        inputView = (LessonInputView) findViewById(R.id.lesson_input_view);
        inputView.setClickListener(this);
        inputView.setNoSendVoiceFunction(!isCanSendVoice);
        inputView.setmContentView(contentView);

//        chatFragment = new ChatFragment();
        //pass parameters to chat fragment
//        Intent intent = getIntent();
//        intent.putExtra(EaseConstant.EXTRA_USER_ID,lesson.getChatid());
//        intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE,EaseConstant.CHATTYPE_GROUP);
//        chatFragment.setArguments(intent.getExtras());
//        getSupportFragmentManager().beginTransaction().add(R.id.rl_chat_contain, chatFragment).commit();

        initInputView();

        //group chat
//        EMGroup group = EMClient.getInstance().groupManager().getGroup(toChatUsername);
//        if (group != null)
//        EMClient.getInstance().groupManager().addGroupChangeListener(this);

        onConversationInit();
        onMessageListInit();
        setRefreshLayoutListener();

    }


//    @Override
//    public boolean onTouchEvent(MotionEvent event) {
//        if (event.getAction() == MotionEvent.ACTION_UP){
//            if (inputView != null && inputView.interceptBackPress()) {
//                return true;
//            }
//        }
//
//        return super.onTouchEvent(event);
//    }

    private boolean showInputView;

    public void onListViewScroll(){
        if (inputView.isRecording()){
            return;
        }
        inputView.interceptBackPress();
    }

    @Override
    public void onBackPressed() {
        if (inputView.isRecording()){
            exitTipDialog();
            return;
        }

        if (!inputView.interceptBackPress()) {
            super.onBackPressed();
        }

    }

    private void exitTipDialog(){
        CommonDialog dialog = new CommonDialog(this);
        dialog.setListener(new CommonDialog.CommonDialogAcitonListener() {
            @Override
            public void positiveAction() {
                if (inputView != null) {
                    inputView.closeRecorder();
                }
            }

            @Override
            public void negertivieAction() {

            }
        });
        dialog.show("是否取消录音？");
        dialog.setPositiveString("是");
        dialog.seCancelString("否");
    }

    //dd


    @Override
    protected void initLocalData() {
        loadLesson();
        getMuteState();
        loadOssTokenWithCache();
        if ("message".equals(from)){
            loadClassDetail();
        }
        if (!TextUtils.isEmpty(toChatUsername)) {
            joinGroup(toChatUsername);
        }

        if (lesson != null && lessonInfo == null) {
            setTitle(lesson.getName());
        }
    }



    @Override
    protected void onResume() {
        super.onResume();
    }

    private void initInputView() {
        inputView.setSubItems(buildInputItems());
    }


    private void updateView() {
        if (lessonInfo != null) {
            topView.updateView(lessonInfo);
        }
        if ("message".equals(from)) {
            toChatUsername = lessonInfo.getChatId();
            if (!TextUtils.isEmpty(toChatUsername)) {
                joinGroup(toChatUsername);
            }
            setTitle(lessonInfo.getName());
            onConversationInit();
            onMessageListInit();
            //
            EMClient.getInstance().chatManager().addMessageListener(this);
            //
        }

    }

    private void updateViewWithPermission(){
        if ("message".equals(from)) {
            isTeacherFriendCircle = currentClasses.isTeacherFriendCircle();
            String role = UserManager.getCurrentUser().getRole();
            isCanSendVoice = RoleUtil.isCanSendVoice(role, isTeacherFriendCircle);
            initInputView();
        }

    }

    @Override
    protected void initListener() {
        titleBar.setOnClickLeftListener(new CommonTitleBar.OnTitleBarClickLeftListener() {
            @Override
            public void onClickLeftBackBtn() {
                if (!inputView.interceptBackPress()) {
                    finish();
                }
            }
        });
        inputView.setVoiceRecorderCallback(new LessonInputVoiceView.VoiceRecorderCallback() {
            @Override
            public void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength) {
                sendVoiceMessage(voiceFilePath, voiceTimeLength);
            }
        });

        listView.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == SCROLL_STATE_TOUCH_SCROLL){
                    onListViewScroll();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                    //ToDO
            }
        });

        topActionView.setOnClickListener(this);
        topView.setViewLestener(this);
        EMClient.getInstance().chatManager().addMessageListener(this);
        registerReceivers();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_expand_top_view:
                if (topView.getVisibility() == View.VISIBLE) {
                    topView.setVisibility(View.GONE);
                    topActionView.setText("展开");
                } else {
                    topActionView.setText("收起");
                    topView.setVisibility(View.VISIBLE);
                }
                break;
        }

    }


    private void loadLesson() {
        if (lesson == null) {
            return;
        }
        showLoading();
        RequestFactory.getCourseLesson(lesson.getId(), new LessonInfoMapper(), new RXObserver<LessonInfo>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(LessonInfo value) {
                if (value != null) {
                    lessonInfo = value;
                    updateView();
                    //获取 聊天记录
                    long startTime = System.currentTimeMillis() / 1000;
                    getChatList(startTime,10,false);
                }
            }

            @Override
            public void onError(Throwable e) {
                dismissLoading();
                resolveException(e);
            }

            @Override
            public void onComplete() {
                dismissLoading();
            }
        });

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceivers();
        UserManager.sharedInstance().clearChatAuthers();
        if (topView != null) {
           int currentPosition =  topView.currentPosition();
            reportLast(currentPosition/1000);
            topView.release();
        }
    }


    @Override
    public void sendInputeMessage(String content) {
        if (TextUtils.isEmpty(content)){
            showErrorTip("请输入内容");
            return;
        }
        sendTextMesage(content);
    }

    @Override
    public void onItemClicked(InputSubItem inputSubItem) {
        switch (inputSubItem.getId()) {
            case 1://禁言 解除禁言
//                if (isMute) {//当前禁言
//                    sendUnmudeMessage();
////                    setUnmuteState(isMute);//解除禁言
//                    inputView.updateMuteState(false);
//                } else {
//                    sendMudeMessage();
//                    inputView.updateMuteState(true);
//                }
                setUnmuteState(isMute);

                break;
            case 2: //明确目标
                startActivityForResult(ClearTargetActivity.getInstent(this), REQUEST_CODE_CLEAR_TARGET);
                break;

            case 3: //分享探讨
                showSendShareDialog();

                break;
            case 4: //提出问题
                startActivityForResult(AskQuestionActivity.getInstent(this), REQUEST_CODE_QUESTION);

                break;
            case 5: //发布总结
                startActivityForResult(LessonSumupActivity.getInstent(this), REQUEST_CODE_SUMUP);

                break;
            case 6: //添加图片
                selectPic();

                break;

        }
    }

    @Override
    public boolean onPressToSpeakBtnTouch(View v, MotionEvent event) {
//        if (checkAudioPermission(this)) {
//            return voiceRecorderView.onPressToSpeakBtnTouch(v, event, new EaseVoiceRecorderView.EaseVoiceRecorderCallback() {
//
//                @Override
//                public void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength) {
////                    sendVoiceMessage(voiceFilePath, voiceTimeLength);
//                    uploadVoice(voiceFilePath, voiceTimeLength);
//                }
//            });
//        }
        return false;
    }

    @Override
    public boolean onCanRecordVoice() {
        return checkAudioPermission(this);
    }

    public static boolean checkAudioPermission(Activity context) {
        if (Build.VERSION.SDK_INT >= 23) {
            int recordAUDIOPermissionState  =
                    ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO);
            int writeStoragePermissionState =
                    ContextCompat.checkSelfPermission(context, WRITE_EXTERNAL_STORAGE);
            if (writeStoragePermissionState != PackageManager.PERMISSION_GRANTED
                    || recordAUDIOPermissionState!= PackageManager.PERMISSION_GRANTED) {
                String[] PERMISSIONS_RECORD_AUDIO = {Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE};
                context.requestPermissions(PERMISSIONS_RECORD_AUDIO, REQUEST_CODE_RECORD_AUDIO);
                return false;
            }
            return true;
        }
        return true;
    }

    private void initMuteState() {
        inputView.updateMuteState(isMute);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_QUESTION && resultCode == Activity.RESULT_OK) {
            String questions = data.getStringExtra("question");
            if (!TextUtils.isEmpty(questions)) {
                sendQuestionMessage(questions);
            }
        } else if (requestCode == REQUEST_CODE_SUMUP && resultCode == Activity.RESULT_OK) {
            String sumup = data.getStringExtra("sumup");
            if (!TextUtils.isEmpty(sumup)) {
                sendSumupMessage(sumup);
            }
        } else if (requestCode == REQUEST_CODE_CLEAR_TARGET && resultCode == Activity.RESULT_OK) {
            String questions = data.getStringExtra("clearTarge");
            if (!TextUtils.isEmpty(questions)) {
                sendClearTargeMessage(questions);
            }
        } else if (requestCode == PhotoPicker.REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            ArrayList<String> photos = null;
            if (data != null) {
                photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
            }
            if (photos != null) {
                sendImagesMessage(photos);
            }
        } else if (requestCode == REQUEST_CODE_FULLSCRAM
                && resultCode == Activity.RESULT_OK){
            if (data != null){
              int currentPage =  data.getIntExtra("currentPage",0);
                topView.setCurrentPage(currentPage);
            }
        }
    }

    private void joinGroup(String gid) {
        RequestFactory.joinGroup(gid, new RXObserver<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Boolean value) {
                //todo 记录已经加入的群
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }




    private ArrayList<InputSubItem> buildInputItems() {
        ArrayList list = new ArrayList();
        if (isCanSendVoice) {
            InputSubItem inputOne = new InputSubItem(R.string.lesson_input_other_one, R.drawable.input_other_one, 1);
            inputOne.setNameActionResorce(R.string.lesson_input_other_one_shit);
            inputOne.setIamgeActionResorce(R.drawable.input_other_one_unenable);
            inputOne.setAction(isMute);
            list.add(inputOne);
            InputSubItem inputTwo = new InputSubItem(R.string.lesson_input_other_two, R.drawable.input_other_two, 2);
            list.add(inputTwo);
            InputSubItem inputThree = new InputSubItem(R.string.lesson_input_other_four, R.drawable.input_other_four, 3);
            list.add(inputThree);
            InputSubItem inputFour = new InputSubItem(R.string.lesson_input_other_three, R.drawable.input_other_three, 4);
            list.add(inputFour);
            InputSubItem inputFive = new InputSubItem(R.string.lesson_input_other_five, R.drawable.input_other_five, 5);
            list.add(inputFive);
        }
        InputSubItem inputSix = new InputSubItem(R.string.lesson_input_other_six, R.drawable.input_other_six, 6);
        list.add(inputSix);
        return list;
    }


    protected void onConversationInit() {
        if (TextUtils.isEmpty(toChatUsername)){
            return;
        }
        conversation = EMClient.getInstance().chatManager().getConversation(toChatUsername, EaseCommonUtils.getConversationType(EaseConstant.CHATTYPE_GROUP), true);
        conversation.markAllMessagesAsRead();
//        final List<EMMessage> msgs = conversation.getAllMessages();
//        int msgCount = msgs != null ? msgs.size() : 0;
//        if (msgCount < conversation.getAllMsgCount() && msgCount < pagesize) {
//            String msgId = null;
//            if (msgs != null && msgs.size() > 0) {
//                msgId = msgs.get(0).getMsgId();
//            }
//            conversation.loadMoreMsgFromDB(msgId, pagesize - msgCount);
//        }

    }


    protected void onMessageListInit() {
        if (TextUtils.isEmpty(toChatUsername)){
            return;
        }
        messageList.init(toChatUsername, EaseConstant.CHATTYPE_GROUP, new EaseCustomChatRowProvider() {
            @Override
            public int getCustomChatRowTypeCount() {
                return 9;
            }

            @Override
            public int getCustomChatRowType(EMMessage message) {
                try {
                    if (message.getType() == EMMessage.Type.IMAGE){//图片
                        if (message.direct() == EMMessage.Direct.SEND){
                            return 4;
                        } else {
                            return 5;
                        }
                    } else if (message.getType() == EMMessage.Type.VOICE){//语音
                        if (message.direct() == EMMessage.Direct.SEND){
                            return 6;
                        } else {
                            return 7;
                        }
                    } else {
                        String type = message.getStringAttribute("type");
                        if ("conclusion".equals(type)) { //干货
                            return 1;
                        } else if ("mute".equals(type) || "unmute".equals(type)){ //解除禁言
                            return 2;
                        }else if ("discuss".equals(type)){ //讨论
                            return 3;
                        }else if ("text".equals(type)|| "target".equals(type) || "question".equals(type)){//文本，目标，问题
                            if (message.direct() == EMMessage.Direct.SEND){
                                return 8;
                            } else {
                                return 9;
                            }
                        }
                    }
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
                return 0;
            }

            @Override
            public EaseChatRow getCustomChatRow(EMMessage message, int position, BaseAdapter adapter) {
                try {
                    if (message.getType() == EMMessage.Type.IMAGE){
                        ChatRowImage rowImage = new ChatRowImage(CaseLearningActivity.this, message, position, adapter);
                        return rowImage;
                    } else if (message.getType() == EMMessage.Type.VOICE){
                        ChatRowVoice voice = new ChatRowVoice(CaseLearningActivity.this, message, position, adapter);
                        return voice;
                    }
                    String type = message.getStringAttribute("type");
                    if ("conclusion".equals(type)) {
                        ChatRowLessonSumup sumup = new ChatRowLessonSumup(CaseLearningActivity.this, message, position, adapter);
                        sumup.setLesson(lesson);
                        return sumup;
                    }else if ("mute".equals(type) || "unmute".equals(type)){
                        ChatRowMute mute = new ChatRowMute(CaseLearningActivity.this, message, position, adapter);
                        return mute;
                    } else if ("discuss".equals(type)){
                        ChatRowDiscuss discuss = new ChatRowDiscuss(CaseLearningActivity.this, message, position, adapter);
                        return discuss;
                    } else if ("text".equals(type)|| "target".equals(type) || "question".equals(type)){
                        ChatRowText text = new ChatRowText(CaseLearningActivity.this, message, position, adapter);
                        return text;
                    }
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
        setListItemClickListener();

        isMessageListInited = true;
    }

    protected void setListItemClickListener() {
        messageList.setItemClickListener(new EaseChatMessageList.MessageListItemClickListener() {

            @Override
            public void onUserAvatarClick(String username) {
//                if(chatFragmentHelper != null){
//                    chatFragmentHelper.onAvatarClick(username);
//                }
            }

            @Override
            public void onUserAvatarLongClick(String username) {
//                if(chatFragmentHelper != null){
//                    chatFragmentHelper.onAvatarLongClick(username);
//                }
            }

            @Override
            public void onLickClick(EMMessage message) {
                //获取mid
                String messageFrom = message.getStringAttribute("message_from","");
                String messageId;
                if ("history".equals(messageFrom)){ //历史消息
                    messageId = message.getMsgId();
                } else  { //实时聊天消息
                    messageId =  message.getStringAttribute("message_id","");
                }
                if (!TextUtils.isEmpty(messageId)){
                    boolean  hasLike =  message.getIntAttribute("has_like",0) == 1;
                    if (hasLike){
                        sendUnlikeMessage(messageId);
                    } else {
                        sendLikeMessage(messageId);
                    }
                    likeChate(messageId);
                }
            }

            @Override
            public void onResendClick(final EMMessage message) {
//                new EaseAlertDialog(CaseLearningActivity.this, com.hyphenate.easeui.R.string.resend, com.hyphenate.easeui.R.string.confirm_resend, null, new EaseAlertDialog.AlertDialogUser() {
//                    @Override
//                    public void onResult(boolean confirmed, Bundle bundle) {
//                        if (!confirmed) {
//                            return;
//                        }
//
//                    }
//                }, true).show();
                messageList.removeSendingMessage(message);
                resendMessage(message);
            }

            @Override
            public void onBubbleLongClick(EMMessage message) {
                if (message.getType() == EMMessage.Type.TXT) {
                    EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
                    String messageContent = txtBody.getMessage();
                    if (!TextUtils.isEmpty(messageContent)) {
                        showCopyCommentDialog(messageContent);
                    }
                }

//                contextMenuMessage = message;
//                if(chatFragmentHelper != null){
//                    chatFragmentHelper.onMessageBubbleLongClick(message);
//                }
            }

            @Override
            public boolean onBubbleClick(EMMessage message) {
//                if(chatFragmentHelper == null){
//                    return false;
//                }
//                return chatFragmentHelper.onMessageBubbleClick(message);
                return false;
            }

        });
    }

    private void showCopyCommentDialog(String comment) {
        if (copyCotentDialog == null) {
            copyCotentDialog = new CopyCommentDialog(this);
        }
        copyCotentDialog.show(comment);
    }

    protected void setRefreshLayoutListener() {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                //// TODO: 2017/5/30
                if (messageList.getItem(0) != null) {
                    long messagetime = messageList.getItem(0).getMsgTime();
                    getChatList(messagetime, 20,true);
                } else {
                    swipeRefreshLayout.setRefreshing(false);
                }
//                getChatList();
//                new Handler().postDelayed(new Runnable() {
//
//                    @Override
//                    public void run() {
//                        if (listView.getFirstVisiblePosition() == 0 && !isloading && haveMoreData) {
//                            List<EMMessage> messages;
//                            try {
//
//                                messages = conversation.loadMoreMsgFromDB(messageList.getItem(0).getMsgId(),
//                                        pagesize);
//                            } catch (Exception e1) {
//                                swipeRefreshLayout.setRefreshing(false);
//                                return;
//                            }
//                            if (messages.size() > 0) {
//                                messageList.refreshSeekTo(messages.size() - 1);
//                                if (messages.size() != pagesize) {
//                                    haveMoreData = false;
//                                }
//                            } else {
//                                haveMoreData = false;
//                            }
//
//                            isloading = false;
//
//                        } else {
//                            showErrorTip("没有更多消息");
//                        }
//                        swipeRefreshLayout.setRefreshing(false);
//                    }
//                }, 600);
            }
        });
    }


    private void getMuteState() {
        String key = "unmute_" + lesson.getChatid();
        RequestFactory.getSystemKey(key, null, new RXObserver<JSONObject>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(JSONObject value) {
                JSONObject data = value.optJSONObject("data");
                if (data != null) {
                    String unmuteValue = data.optString("value", "1");
                    if ("1".equals(unmuteValue)) {
                        isMute = false;
                    } else if ("0".equals(unmuteValue)) {
                        isMute = true;
                    }
                    initMuteState();
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void setUnmuteState(final boolean unmute) {
        showLoading();
        String key = "unmute_" + lesson.getChatid();
        String value;
        if (unmute) {
            value = "1"; //不禁言
        } else {
            value = "0"; //禁言
        }
        RequestFactory.setSystemKeyValue(key, value, null, new RXObserver<JSONObject>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(JSONObject value) {
                if (isMute) {//当前禁言
                    sendUnmudeMessage();
                    inputView.updateMuteState(false);
                } else {
                    sendMudeMessage();
                    inputView.updateMuteState(true);
                }
                isMute = !unmute;
                initMuteState();
            }

            @Override
            public void onError(Throwable e) {
                dismissLoading();
                resolveException(e);
            }

            @Override
            public void onComplete() {
                dismissLoading();

            }
        });
    }


    /********************************发送消息*************************************/

    protected void sendHXTextMessage(EMMessage message) {
        HXChatMessage chatMessage = new HXChatMessage();
        chatMessage.setType("txt");
        EMTextMessageBody body = (EMTextMessageBody)message.getBody();
        chatMessage.setMessage(body.getMessage());
        chatMessage.setFrom(message.getFrom());
        chatMessage.setGroupId(lesson.getChatid());
        try {
            chatMessage.addExt("type",message.getStringAttribute("type"));
            chatMessage.addExt("author",message.getJSONObjectAttribute("author"));
            chatMessage.addExt("identifier",message.getStringAttribute("identifier"));
            chatMessage.addExt("em_ignore_notification",message.getBooleanAttribute("em_ignore_notification"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        message.setStatus(EMMessage.Status.INPROGRESS);
        message.setDirection(EMMessage.Direct.SEND);
        messageList.addSendMessage(message);
        sendMessage(chatMessage);
//        sendMessage();
    }

    private void sendHXVoiceMessage(EMMessage message){
        EMVoiceMessageBody body = (EMVoiceMessageBody) message.getBody();
        HXChatMessage chatMessage = new HXChatMessage();
        chatMessage.setType("audio");
        chatMessage.setFrom(message.getFrom());
        chatMessage.setGroupId(lesson.getChatid());
        chatMessage.setFpath(body.getRemoteUrl());
        chatMessage.setLength(body.getLength());
        try {
            chatMessage.addExt("type",message.getStringAttribute("type"));
            chatMessage.addExt("author",message.getJSONObjectAttribute("author"));
            chatMessage.addExt("identifier",message.getStringAttribute("identifier"));
            chatMessage.addExt("em_ignore_notification",message.getBooleanAttribute("em_ignore_notification"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        sendMessage(chatMessage);
    }

    private void resendHXVoiceMessage(EMMessage message) {
        EMVoiceMessageBody body = (EMVoiceMessageBody) message.getBody();
        if (body != null) {
            sendVoiceMessage(body.getLocalUrl(), body.getLength());
        }
    }

    private void resendHXImageMessage(EMMessage message) {
        EMImageMessageBody body = (EMImageMessageBody) message.getBody();
        if (body != null) {
            String path = body.getLocalUrl();
            ArrayList paths = new ArrayList();
            paths.add(path);
            sendImagesMessage(paths);
//            uploadPhoto(paths,message);
        }
    }

    private void sendHXImageMessage(EMMessage message) {
        EMImageMessageBody body = (EMImageMessageBody) message.getBody();
        HXChatMessage chatMessage = new HXChatMessage();
        chatMessage.setType("img");
        chatMessage.setFrom(message.getFrom());
        chatMessage.setGroupId(lesson.getChatid());
        chatMessage.setFpath(body.getRemoteUrl());//
        chatMessage.setWidth(body.getWidth());
        chatMessage.setHeight(body.getHeight());
        try {
            String type = message.getStringAttribute("type");
            if (type != null) {
                chatMessage.addExt("type", type);
            }
            JSONObject auther = message.getJSONObjectAttribute("author");
            if (auther != null) {
                chatMessage.addExt("author", auther);
            }
            chatMessage.addExt("identifier", message.getStringAttribute("identifier"));
            chatMessage.addExt("em_ignore_notification", message.getBooleanAttribute("em_ignore_notification"));
        } catch (Exception e) {
            e.printStackTrace();
        }
//        message.setStatus(EMMessage.Status.INPROGRESS);
//        message.setDirection(EMMessage.Direct.SEND);
//        messageList.addSendMessage(message);
        sendMessage(chatMessage);
    }



    protected void sendMessage(EMMessage messag, String type) {
        EMMessage message = addMessageAttribute(messag, type);
        if (canSendMessae()){
            if (message.getType() == EMMessage.Type.TXT){
                sendHXTextMessage(message);
            } else if (message.getType() == EMMessage.Type.VOICE){
                sendHXVoiceMessage(message);
            } else if (message.getType() == EMMessage.Type.IMAGE){
                sendHXImageMessage(message);
            }
        }


//        EMClient.getInstance().chatManager().sendMessage(message);
        //refresh ui
        if (isMessageListInited) {
            //
//            message.setStatus(EMMessage.Status.INPROGRESS);
//            messageList.AddNewMessage(message);
//            messageList.refreshSelectLast();
        }
    }

    private boolean canSendMessae(){
        if (isMute) {
            String role = UserManager.getCurrentUser().getRole();
            if (RoleUtil.isCanMute(role)) {
                ToastUtil.showNewErrorMsg("当前仅老师可发言");
                return false;
            }
        }
        return true;
    }

    //发送图片消息
    protected void sendImageMessage(String imagePath,String remoteUrl,EMMessage locaMessage) {
//        final EMMessage message = EMMessage.createSendMessage(EMMessage.Type.IMAGE);
//        message.setTo("");
//        EMImageMessageBody body = new EMImageMessageBody("",imagePath,imagePath);
//        // 默认超过100k的图片会压缩后发给对方，可以设置成发送原图
//        body.setSendOriginalImage(false);
//        message.addBody(body);
        try {
            if (canSendMessae()) {
                EMMessage message = EMMessage.createImageSendMessage(imagePath, false, toChatUsername);
                EMImageMessageBody body = (EMImageMessageBody) message.getBody();
                body.setRemoteUrl(remoteUrl);
                EMMessage messageshit = addMessageAttribute(message, "img");
                message.setAttribute("identifier", locaMessage.getStringAttribute("identifier"));
                sendHXImageMessage(messageshit);
            }
        } catch (HyphenateException e) {
            e.printStackTrace();
        }
    }

    //发送声音消息
    protected void sendVoiceMessage(String filePath, int length, String remoteUrl, EMMessage locaMessage) {
        try {
            EMMessage message = EMMessage.createVoiceSendMessage(filePath, length, toChatUsername);
            EMVoiceMessageBody voice = (EMVoiceMessageBody) message.getBody();
            voice.setRemoteUrl(remoteUrl);
            EMMessage messageshit = addMessageAttribute(message, "audio");
            messageshit.setAttribute("identifier", locaMessage.getStringAttribute("identifier"));

            sendHXVoiceMessage(messageshit);
        } catch (HyphenateException e) {
            e.printStackTrace();
        }
    }




    //发送普通文本消息
    private void sendTextMesage(String content) {
        if (canSendMessae()) {
            EMMessage message = EMMessage.createTxtSendMessage(content, toChatUsername);
            sendMessage(message, "text");
        }
    }

    //发送问题
    private void sendQuestionMessage(String content) {
        EMMessage message = EMMessage.createTxtSendMessage(content, toChatUsername);
        sendMessage(message, "question");
    }

    //明确目标
    private void sendClearTargeMessage(String content) {
        EMMessage message = EMMessage.createTxtSendMessage(content, toChatUsername);
        sendMessage(message, "target");
    }

    //发送总结
    private void sendSumupMessage(String content) {
        EMMessage message = EMMessage.createTxtSendMessage(content, toChatUsername);
        sendMessage(message, "conclusion");
    }


    //分享
    private void sendShareMessage() {
        EMMessage message = EMMessage.createTxtSendMessage("share", toChatUsername);
        sendMessage(message, "discuss");
    }

    //禁言
    private void sendMudeMessage() {
        EMMessage message = EMMessage.createTxtSendMessage("mute", toChatUsername);
        sendMessage(message, "mute");
    }

    //解除禁言
    private void sendUnmudeMessage() {
        EMMessage message = EMMessage.createTxtSendMessage("unmute", toChatUsername);
        sendMessage(message, "unmute");
    }

    //点赞
    private void sendLikeMessage(String msgid) {
        EMMessage message = EMMessage.createTxtSendMessage("like", toChatUsername);
        message.setChatType(EMMessage.ChatType.GroupChat);
        message.setAttribute("type", "like");
        message.setAttribute("em_ignore_notification", true);
        message.setAttribute("message_id", msgid);
        message.setAttribute("sender_id", UserManager.getCurrentUser().getID());
        EMClient.getInstance().chatManager().sendMessage(message);//
    }

    //取消点赞
    private void sendUnlikeMessage(String msgid) {
        EMMessage message = EMMessage.createTxtSendMessage("unlike", toChatUsername);
        message.setChatType(EMMessage.ChatType.GroupChat);
        message.setAttribute("type", "unlike");
        message.setAttribute("em_ignore_notification", true);
        message.setAttribute("message_id", msgid);
        message.setAttribute("sender_id", UserManager.getCurrentUser().getID());
        EMClient.getInstance().chatManager().sendMessage(message);//
    }



    public void resendMessage(EMMessage message) {
        if (canSendMessae()) {
            if (message.getType() == EMMessage.Type.TXT) {
                sendHXTextMessage(message);
            } else if (message.getType() == EMMessage.Type.VOICE) {
                resendHXVoiceMessage(message); //重新发送
            } else if (message.getType() == EMMessage.Type.IMAGE) {
                resendHXImageMessage(message);
            }
        }

//        message.setStatus(EMMessage.Status.CREATE);
//        EMClient.getInstance().chatManager().sendMessage(message);
//        messageList.refresh();
    }

    //发送声音消息
    private void sendVoiceMessage(final String localPath, final int length) {
        if (canSendMessae()){
            EMMessage message = EMMessage.createVoiceSendMessage(localPath, length, toChatUsername);
            EMVoiceMessageBody voice = (EMVoiceMessageBody) message.getBody();
            voice.setLocalUrl(localPath);
            message =  addMessageAttribute(message, "audio");

            message.setStatus(EMMessage.Status.INPROGRESS);
            message.setDirection(EMMessage.Direct.SEND);
            messageList.addSendMessage(message);
            //
//            try {
//                voiceIdentifi = message.getStringAttribute("identifier");
//            } catch (HyphenateException e) {
//                e.printStackTrace();
//            }
            uploadVoice(localPath,length,message);
        }
    }


    //发送图片消息
    private void sendImagesMessage(ArrayList<String> photos) {
        //TODO 提示框
        if (canSendMessae()){
            EMMessage message = EMMessage.createImageSendMessage(photos.get(0), false, toChatUsername);
            EMImageMessageBody body = (EMImageMessageBody) message.getBody();
            body.setLocalUrl(photos.get(0));
            message =  addMessageAttribute(message, "img");

            message.setStatus(EMMessage.Status.INPROGRESS);
            message.setDirection(EMMessage.Direct.SEND);
            messageList.addSendMessage(message);

            uploadPhoto(photos,message);

        }
    }


    protected EMMessage addMessageAttribute(EMMessage message, String type) {
        if (message == null) {
            return null;
        }
        if (type != null) {
            message.setAttribute("type", type);
        }
        User user = UserManager.getCurrentUser();
        if (user != null) {
            message.setFrom(user.getID());
            JSONObject object = new JSONObject();
            try {
                object.put("id", user.getID());
                object.put("name", user.getName());
                object.put("avatar", user.getAvatar());
                object.put("role", user.getRole());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            message.setAttribute("author", object);
            String identi = System.currentTimeMillis() + user.getID();
            message.setAttribute("identifier", identi);
            message.setAttribute("em_ignore_notification", true);
        }
        message.setChatType(EMMessage.ChatType.GroupChat);

        return message;

    }

    /********************************接收消息*************************************/


    @Override
    public void onMessageReceived(List<EMMessage> messages) {
        //收到消息
        ArrayList newMeesages = new ArrayList();
        ArrayList likeMeesages = new ArrayList();
        for (EMMessage message : messages) {
//            message.getJSONObjectAttribute()
//            Log.e("HEHE","-----------"+message.toString());
//            Log.e("HEHE","-----------"+message.getBody().toString());
            message.getStringAttribute("","");

            String username = null;
            // group messagem
            if (message.getChatType() == EMMessage.ChatType.GroupChat || message.getChatType() == EMMessage.ChatType.ChatRoom) {
                username = message.getTo();
            } else {
                // single chat message
                username = message.getFrom();
            }

            // if the message is for current conversation
            if (username.equals(toChatUsername) || message.getTo().equals(toChatUsername)) {

                String type = null;
                try {
                     type =  message.getStringAttribute("type","");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (type != null){
                    try {
                        if ("like".equals(type) || "unlike".equals(type)) {
                            String senderid =  message.getStringAttribute("sender_id","");
                            if (!UserManager.getCurrentUser().getID().equals(senderid)){//自己不处理
                                likeMeesages.add(message);
                            }
                        } else {
                            if (UserManager.getCurrentUser().getID().equals(message.getFrom())){
                                message.setDirection(EMMessage.Direct.SEND);
                            }
                            newMeesages.add(message);
                            matchMuteMessage(message); //
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    newMeesages.add(message);
                }
            }
            //改变禁言状态
        }
        if (newMeesages.size() > 0){
            messageList.AddNewMessage(newMeesages);
        }
        if (likeMeesages.size() > 0){
            messageList.updateLikeMessageStatus(likeMeesages);
        }

    }

    private void matchMuteMessage(EMMessage message) {
        try {
            String  type = message.getStringAttribute("type");
            if (type != null) {
                if ("mute".equals(type)) {
                    isMute = true;
                } else if ("unmute".equals(type)) { //
                    isMute = false;
                }
            }
        } catch (HyphenateException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onCmdMessageReceived(List<EMMessage> messages) {
        if (isMessageListInited) {
            messageList.refresh();
        }
    }

    @Override
    public void onMessageRead(List<EMMessage> messages) {
        if (isMessageListInited) {
            messageList.refresh();
        }
    }

    @Override
    public void onMessageDelivered(List<EMMessage> messages) {
        if (isMessageListInited) {
            messageList.refresh();
        }
    }

    @Override
    public void onMessageChanged(EMMessage message, Object change) {
        if (isMessageListInited) {
            messageList.refresh();
        }
    }


    /**********/
    private void showSendShareDialog() {
        CommonDialog dialog = new CommonDialog(this);
        dialog.setListener(new CommonDialog.CommonDialogAcitonListener() {
            @Override
            public void positiveAction() {
                sendShareMessage();
            }

            @Override
            public void negertivieAction() {

            }
        });
        dialog.show("是否要开启分享探讨？");
    }


    //// TODO: 2017/6/3
    private void selectPic() {
        PhotoPicker.builder()
                .setPhotoCount(1)
                .setShowCamera(true)
                .setPreviewEnabled(false)
                .setIsSendImage(true)
                .setSelected(null)
                .start(this);
    }


    @Override
    public void fullScreen(int currentItem) {
        Intent intent = FullScreenAudioActivity.newIntent(this, lessonInfo, currentItem);
//        startActivity(intent);
        startActivityForResult(intent,REQUEST_CODE_FULLSCRAM);
    }



    //上报当前学习进度
    private void reportLast(int stamp){
        RequestFactory.setCourseLastReport(lesson.getId(), stamp, null, new RXObserver() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(Object value) {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    //发送消息
    private void sendMessage(final HXChatMessage message){
        RequestFactory.sendHXChat(message, null, new RXObserver() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Object value) {

            }

            @Override
            public void onError(Throwable e) {
                if (e instanceof SendTimeException){
                    showErrorTip("只能发布一次总结");
                    //TODO移除消息
                } else {
                    resolveException(e);
                    messageList.setMessageFailed(message.identifier());
                    //设置失败
                    //setMessageFailed
//                    setMessageFailed

                }
            }

            @Override
            public void onComplete() {

            }
        });

    }

    //上传音频
    private void uploadVoice(final String localPath, final int length,final EMMessage message) {
        ALUploadFileParam param = new ALUploadFileParam();
        param.setUid(UserManager.getCurrentUser().getID());
        param.addPathe(localPath);
        param.setOssClient(ossClient);
        param.setOssToken(ossToken);
        RequestFactory.uploadVoiceFileToALY(param, new RXObserver<ArrayList<String>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ArrayList<String> value) {
                if (value != null && value.size() > 0) {
                    String remotePath = value.get(0);
                    if (remotePath != null) {
                        sendVoiceMessage(localPath, length, remotePath,message);
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                resolveException(e);
                //设置失败 ---
                messageList.setMessageFailed(message);
//                messageList.setMessageFailed(message);
            }

            @Override
            public void onComplete() {
            }
        });
    }


    //上传图片
    private void uploadPhoto(final ArrayList<String> selectedPhotos,final  EMMessage message) {
//        showLoading();//
        ALUploadFileParam param = new ALUploadFileParam();
        param.setUid(UserManager.getCurrentUser().getID());
        param.setPathes(selectedPhotos);
        param.setOssClient(ossClient);
        param.setOssToken(ossToken);
        RequestFactory.uploadFileToALY(param, new RXObserver<ArrayList<String>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ArrayList<String> value) {
                for (int i = 0; i < value.size(); i++) {
                    sendImageMessage(selectedPhotos.get(i),value.get(i),message);
                }
            }

            @Override
            public void onError(Throwable e) {
//                resolveException(e);
                messageList.setMessageFailed(message);
//                showErrorTip(e.getMessage());
//                dismissLoading();
            }

            @Override
            public void onComplete() {
                dismissLoading();
            }
        });
    }


    private void loadOssTokenWithCache() {
        String uid = UserManager.getCurrentUser().getID();
        CacheFactory.loadOssToken(uid, new RXObserver<OssToken>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(OssToken value) {
                ossToken = value;
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                if (ossToken != null && !TextUtils.isEmpty(ossToken.getSecurityToken())) {
                    buildOssClient();
                } else {
                    loadOssToken();
                }
            }
        });

    }

    private void buildOssClient(){
        if (ossToken != null) {
            ossClient = ALUploadFileParam.loadOSSClient(this, ossToken);
        }
    }

    private void loadOssToken(){
        RequestFactory.getOssToken(new OssTokenMapper(), new RXObserver<OssToken>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(OssToken value) {
                if (value != null && !TextUtils.isEmpty(value.getSecurityToken())){
                    ossToken = value;
                    buildOssClient();
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }


    private void registerReceivers(){
        IntentFilter filter = new IntentFilter();
        filter.addAction(RuiXConstant.NOTICE_RELEASE_LESSON_SUCCESS_PRACTICE);
        registerReceiver(myReceiver, filter);
    }

    private void unregisterReceivers(){
        if (myReceiver != null){
            unregisterReceiver(myReceiver);
        }
    }

    private BroadcastReceiver myReceiver = new BroadcastReceiver(){

        @Override
        public void onReceive(Context context, Intent intent) {
            if (RuiXConstant.NOTICE_RELEASE_LESSON_SUCCESS_PRACTICE.equals(intent.getAction())){
                finish();
            }
        }

    };

    private void getChatList(long startTime,int limit,final boolean loadMore){
        if (lesson == null){
            return;
        }
        if (!loadMore){
            showLoading();
        }
        RequestFactory.getChatList(lesson.getChatid(), startTime, limit, new  MessageMapper(), new RXObserver<ArrayList<EMMessage>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ArrayList<EMMessage> value) {
                if (value != null && value.size() > 0){
//                    if (loadMore){
//                        messageList.AddMessage(value);
//                    } else {
//                    }
                    messageList.AddMessage(value);
                } else {
                    showErrorTip("没有更多消息");
                }
            }

            @Override
            public void onError(Throwable e) {
                if (loadMore){
                    swipeRefreshLayout.setRefreshing(false);
                } else {
                    dismissLoading();
                }
                resolveException(e);
            }

            @Override
            public void onComplete() {
                if (loadMore){
                    swipeRefreshLayout.setRefreshing(false);
                } else {
                    dismissLoading();
                }

            }
        });

    }

    //点赞
    private void likeChate(String messageid){
        RequestFactory.chatLike(messageid, null, new RXObserver() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Object value) {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

    }


    private void loadClassDetail(){
        if (currentClasses == null){
            return;
        }
        RequestFactory.classDetail(currentClasses.getID(), new ClasssDetailMapper(currentClasses.getID()), new RXObserver<ClassDetail>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ClassDetail value) {
                if (value != null) {
                    updateViewWithPermission();
                }
            }

            @Override
            public void onError(Throwable e) {
                resolveException(e);
            }

            @Override
            public void onComplete() {

            }
        });
    }






}
